import axios from 'axios'
import { ElNotification, ElMessage } from 'element-plus'
const SERVER_IP = import.meta.env.VITE_APP_API_IP
const SERVER_PORT = import.meta.env.VITE_APP_API_PORT
const request = axios.create({
  baseURL: `http://${SERVER_IP}:${SERVER_PORT}/admin`,
})
import router from '@/router'
request.interceptors.request.use((config) => {
  const token = localStorage.getItem('Authorization')
  if (token) {
    config.headers['Authorization'] = token
  }
  return config
})

request.interceptors.response.use(
  (response) => {
    if (response.data.code === 0) {
      ElMessage.error(response.data.message)
      return Promise.reject(response.data.message)
    }
    return response.data
  },
  async (error) => {
    if (error.response && error.response.status === 401) {
      // 401 特殊处理：清除无效 token、跳转到登录页
      localStorage.removeItem('Authorization') // 清除本地存储的 token
      ElNotification({
        title: '认证失败',
        message: '登录已过期，请重新登录',
        type: 'warning',
      })
      router.push('/login') // 跳转到登录页
    } else {
      ElNotification({
        title: '错误',
        message: '网络异常！请稍后重试！',
        type: 'error',
      })
    }
    return Promise.reject(error)
  }
)

export default request
